// pages/propagate/index.ts

import {getRecordSubmitDetails, getRecordDetails, employRecord} from "../../service/api/api-propagate";
import {fontSizeCalc, handleCode, handleErrCode} from "../../utils/util";

const rules = [{
    name: "reward",
    rule: ["required","isAmount","range:[0.01,100]"],
    msg: ["积分不能为空","请输入数字，保留两位小数","范围0.01-100"]
}]

Page({

    /**
     * 页面的初始数据
     */
    data: {
        recordId: 0,// 纪录id
        record: {
            isEmploy: 1
        },// 纪录详情
        access: {} as any,// 当前用户权限
        currentUser: {},// 当前用户信息
        options: '',
        isAdmin: false,// 是否是管理员查看详情
        modal: false,// 是否显示弹窗
        modalReward: '',// 弹窗输入的积分
        imgUrl: [],// 图片Url
        galleryShow: false,// 是否显示图片预览
        iconSize: fontSizeCalc(40),
        tabFontSize: fontSizeCalc(28),
        labelSize: fontSizeCalc(28),
        inputSize: fontSizeCalc(32),
        btnHeight: fontSizeCalc(60) + 'rpx',
        btnLineHeight: fontSizeCalc(36) + 'rpx',
        btnWidth: fontSizeCalc(320) + 'rpx',
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        const recordId = options.id || 0;
        const {globalData: {access, currentUser}} = getApp();
        this.setData({
            access,
            recordId,
            isAdmin: options.isAdmin === 'true',
            currentUser,
            options: JSON.stringify(options)
        })
        this.getRecordDetail(recordId);
    },
    /**
     * 处理一下凭证类型
     * @param data
     */
    handleVoucherType({voucherType}) {
        switch (voucherType) {
            case 10:
                return '链接'
            case 11:
                return '口令'
            case 20:
                return '图片'
            case 30:
                return '视频'
            case 40:
                return '文件'
            default:
                return ''
        }
    },

    /**
     * 处理一下纪录状态
     * @param data
     */
    handleRecordType({state, isCancel}) {
        return {
            typeName: state === 1 ? '已提交' : (isCancel === 0 ? '正在发布' : '已撤回'),
            bgColor: state === 1 ? '#389E0D' : (isCancel === 0 ? '#91caff' : '#FF814A'),
        }
    },

    /**
     * 处理一下管理员进入时的纪录状态
     * @param data
     */
    handleAdminRecordType({isEmploy}) {
        return {
            typeName: isEmploy === 1 ? '已收录' : '未收录',
            bgColor: isEmploy === 1 ? '#389E0D' : '#F5A34D',
        }
    },

    /**
     * 处理一下凭证内容
     * @param list
     * @param voucherType
     */
    handleVoucherOriginalsType(list = [], {voucherType = 0}) {
        return list.map(item => {
            let voucherName = '';
            if (voucherType === 20) {
                let {content = ''} = item;
                const hashIndex = content?.indexOf('?');
                content = hashIndex !== -1 ? content?.substring(0, hashIndex) : content;
                voucherName = decodeURI((content.split('/').pop() || '').replace(/[\?].*$/g, ''));
            }
            return {
                ...item,
                voucherName
            }
        })
    },

    /**
     * 通过id获取纪录详情
     * @param id
     */
    async getRecordDetail(id) {
        let _that = this;
        wx.showLoading({
            title: '查询中...'
        })
        const isAdmin = this.data.isAdmin;
        // 执行搜索函数
        await (isAdmin ? getRecordDetails : getRecordSubmitDetails)({id}).then(async (response) => {
            wx.hideLoading();
            const newRecord = response.data || {};
            const {
                typeName,
                bgColor
            } = isAdmin ? this.handleAdminRecordType(newRecord) : this.handleRecordType(newRecord);
            newRecord.voucherTypeName = this.handleVoucherType(newRecord);
            newRecord.voucherOriginals = this.handleVoucherOriginalsType(newRecord.voucherOriginals || [], newRecord)
            newRecord.bgColor = bgColor;
            newRecord.typeName = typeName;
            _that.setData({
                record: response.data || {}
            })
        }).catch(error => {
            console.warn(error)
            wx.showToast({
                title: error || '查询失败',
                icon: 'error',
                duration: 1500
            })
            wx.hideLoading();
        }).finally(() => {
            wx.hideLoading();
        })
    },

    /**
     * 显示弹窗弹窗
     */
    showModal() {
        this.setData({
            modal: true,
            modalReward: this.data.record?.reward || '',
        })
    },

    /**
     * 关闭弹窗弹窗
     */
    modalCancel() {
        this.setData({
            modal: false,
            modalReward: '',
        })
    },

    /**
     * 收录确认弹窗
     */
    modalConfirmFun() {
        const {record, modalReward} = this.data || {}
        let formData = {
            reward: modalReward
        };
        this.selectComponent("#form").validate(formData, rules).then(res => {
            this.employFun({...formData, id: record.id || 0})
        }).catch(errors => {
            console.log(errors)
        })
    },

    /**
     * 收录确认弹窗
     */
    async employFun(params) {
        wx.showLoading({
            title: '请稍后...'
        })
        // 执行搜索函数
        await employRecord(params).then(async (res) => {
            if (res?.code === 0) {
                handleCode(res, '收录成功');
                setTimeout(() => {
                    if (this.data.isAdmin) {// 管理员
                        wx.redirectTo({
                            url: '/pages/propagateAdmin/index',
                        })
                    } else {
                        wx.redirectTo({
                            url: '/pages/propagate/index',
                        })
                    }
                }, 1000)
            } else {
                handleErrCode()
            }
            wx.hideLoading();
            this.modalCancel();
        }).catch(error => {
            handleErrCode(error, 'none')
            wx.hideLoading();
            this.modalCancel();
        }).finally(() => {
            wx.hideLoading();
        })
    },

    /**
     * 显示弹窗弹窗
     */
    showGalleryFun(imgUrl: any) {
        this.setData({
            galleryShow: true,
            imgUrl,
        })
    },

    /**
     * 关闭弹窗弹窗
     */
    hideGalleryFun() {
        this.setData({
            galleryShow: false,
            imgUrl: [],
        })
    },

    /**
     * 凭证类型点击
     */
    voucherItemClick(e: any) {
        const {voucherType = 0, voucherOriginals = []} = this.data.record || {};
        // const {content = '',voucherName = ''} = e.currentTarget.dataset.item || {};
        switch (voucherType) {
            case 10: // '链接'
                break;
            case 11: // '口令'
                break;
            case 20: // '图片''
                this.showGalleryFun(
                    voucherOriginals.map(item => {
                        return {
                            src: item.content,
                            desc: item.voucherName
                        }
                    }))
                break;
            case 30: // '视频'
                break;
            case 40: // '文件'
                break;
            default:
                return ''
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        wx.hideShareMenu({
            menus: ['shareAppMessage', 'shareTimeline'],// 隐藏分享到朋友和分享到朋友圈
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    taskExecuteShareFun() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {
    }
})